import {Base} from '../../utils/base.js';

class Order extends Base {
  constructor() {
    super();
    this._storageKeyName='newOrder';
  }

  /**
  * 获取订单信息
  */
 getOrderInfo(id, callback){
  var params = {
    url: 'order/detail?orderId=' + id,
    sCallback:function (res) {
      callback && callback(res.data)
    }
  };
  this.request(params);
 }

 /**
  * 获取用户订单列表
  * @param {*} page 
  * @param {*} callback 
  */
 getOrderList(page, callback) {
  var params = {
    url: 'order/userOlist?page=' + page,
    sCallback:function (res) {
      callback && callback(res.data)
    }
  };
  this.request(params);
 }

  /**
   * 下订单，生成订单号
   * @param {*} data 
   * @param {*} callback 
   */
  doOrder(data, callback) {
    var that = this;
    var params = {
      url: 'order/placeOrder',
      type: 'POST',
      data :{
        products: data
      },
      sCallback: function(res){
        that.execSetStorageSync(true);
        callback&&callback(res.data);
      },
      eCallbask: function(res){

      }
    }

    this.request(params);
  }

  /* 根据服务端返回的参数调取小程序支付方法 */
  execPay(orderId, callback){
    var allParams = {
        url: 'pay/preOrder',
        type:'post',
        data:{orderId:orderId},
        sCallback: function (data) {
            var timeStamp= data.timeStamp;
            if(timeStamp) { //可以支付
                wx.requestPayment({
                    'timeStamp': timeStamp.toString(),
                    'nonceStr': data.nonceStr,
                    'package': data.package,
                    'signType': data.signType,
                    'paySign': data.paySign,
                    success: function () {
                        callback && callback(2);
                    },
                    fail: function () {
                        callback && callback(1);
                    }
                });
            }else{
                callback && callback(0);
            }
        }
    };
    this.request(allParams);
  }

  /**
  * 是否有新订单
  */
 hasNewOrder(){
  var flag = wx.getStorageSync(this._storageKeyName);
  return flag;
 }

  /*本地缓存 保存／更新*/
  execSetStorageSync(data){
    wx.setStorageSync(this._storageKeyName,data);
}
}

// 是否开启支付
Order.onPay = false;
export {Order};